<?php
namespace App\Handlers;

use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;
require_once __DIR__ . '\..\..\vendor\workerman\workerman\Autoloader.php';

$ws_worker = new Worker("websocket://0.0.0.0:2000");

// 启动4个进程对外提供服务
$ws_worker->count = 4;


$ws_worker->uidConnections = array();
$ControllerArray=array(
    'U'=>'UserController',
    'G'=>'AdminController',
);
// 当收到客户端发来的数据后返回hello $data给客户端
$ws_worker->onMessage = function($connection, $data) use ($ws_worker,$ControllerArray)
{
    if(!isset($connection->uid))
    {
        $connection->uid=$connection->id;
        $ws_worker->uidConnections[$connection->id]=$connection;
    }
    $data=json_decode($data,true);
    $controller=$data['Con']?$data['Con']:'';
    $version=$data['Ver']?$data['Ver']:'v1';
    $function=$data['Fun']?$data['Fun']:'error';
    $controller=isset($ControllerArray[$controller])?$ControllerArray[$controller]:'';
    $class_name='Http\Controllers';

    if(!empty($version))
    {
        $class_name.='\\'.$version;
    }
    $class_name.='\\'.$controller;
    if(!file_exists(app_path($class_name.'.php')))
    {
        http_response_code(404);
        exit();
    }
    $class_name='\App\\'.$class_name;
    if(method_exists(new $class_name,$function))
    {
        $a=new $class_name;
        sendMessageByUid(1,$a->$function($data));
    }
    else
    {
        http_response_code(405);
        exit();
    }


    ////取得访问接口信息和传输值，找到对应方法处理
};
$ws_worker->onConnect = function($connection)
{
    echo "new connection from ip " . $connection->getRemoteIp() . "\n";

    ///验证用户，存储连接信息
};

function sendMessageByUid($uid, $message)
{
    global $ws_worker;
    if(isset($ws_worker->uidConnections[$uid]))
    {
        $connection = $ws_worker->uidConnections[$uid];
        $connection->send($message);
        return true;
    }
    return false;
}

// 运行worker
Worker::runAll();
/**
ws = new WebSocket("ws://127.0.0.1:2000");
ws.onopen = function() {
alert("连接成功");
ws.send('tom');
alert("给服务端发送一个字符串：tom");
};
ws.onmessage = function(e) {
alert("收到服务端的消息：" + e.data);
};
**/